package jdk.thread.tool;

import cn.hutool.core.util.NumberUtil;
import cn.hutool.core.util.RandomUtil;
import lombok.SneakyThrows;

import java.util.concurrent.Exchanger;
import java.util.concurrent.TimeUnit;

/**
 * 线程间交换数据
 * 很简单的用法，1为无限时等待交换数据，2为有限时
 */
public class ExchangerTest {

    public static void main(String[] args) {
        Exchanger<Integer> exchanger = new Exchanger<>();
        Te t1 = new Te("一", exchanger);
        Te t2 = new Te("二", exchanger);
        t1.start(); t2.start();
    }
}


class Te extends Thread{

    Exchanger<Integer> exchanger;
    String name;

    public Te(String name, Exchanger<Integer> exchanger) {
        this.name = name;
        this.exchanger = exchanger;
    }

    @SneakyThrows
    @Override
    public void run() {
        int a = RandomUtil.randomInt(0, 1000);
        System.out.println("线程["+name+"]的A值为"+a);
        Thread.sleep(a);
        int b = exchanger.exchange(a, 1000, TimeUnit.MILLISECONDS);
        System.out.println("线程["+name+"]的B值为"+b);
    }
}